package com.example.demo20241128.demos.filter;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
@Order(2)
@Slf4j
public class RequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Enumeration<String> headerKeys = request.getHeaderNames();
        Map<String, Object> headers = new HashMap<>();
        while (headerKeys.hasMoreElements()) {
            String key = headerKeys.nextElement();
            headers.put(key, request.getHeader(key));
        }
        Object[] params = new Object[] { request.getRequestURI(), headers, JSONUtil.toJsonStr(request.getParameterMap())};
        log.info("request body：请求地址：{}-请求header-{}-请求body-{}", params);
        long start = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        // 记录接口请求耗时
        log.info("API:[{}]-end-{}ms", request.getRequestURI(), System.currentTimeMillis() - start);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
